//
//  MainController.m
//  soccer
//
//  Created by 上官千城 on 15/9/11.
//  Copyright (c) 2015年 上官千城. All rights reserved.
//

#import "OMainController.h"

@interface OMainController ()

@end

@implementation OMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //创建表
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 100) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
      self.user = [OUserInfo getInfo];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backTo)];
    
 
}


-(void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
    NSLog(@"nickeName == %@,nickName = %@,userSign = %@,signature = %@",self.user.nickName,self.nickName.text,self.user.sign,self.signature.text);
    
    if (self.user.nickName != self.nickName.text || self.user.sign != self.signature.text) {
        
        //        return;
        
        [self refreshData];
    }
}


-(void)getPosition
{
    
    if (IS_IOS8) {
        [UIApplication sharedApplication].idleTimerDisabled = TRUE;
       CLLocationManager *locationmanager = [[CLLocationManager alloc] init];
        [locationmanager requestAlwaysAuthorization];        //NSLocationAlwaysUsageDescription
        [locationmanager requestWhenInUseAuthorization];     //NSLocationWhenInUseDescription
        locationmanager.delegate = self;
        

        [[CCLocationManager shareLocation]getCity:^(NSString *cityString) {
            NSLog(@"%@",cityString);
            self.zone = cityString;
            [self.tableView reloadData];
            
        }];
                       
    }
}


-(void)refreshData
{
    if ([self.user.nickName isEqualToString:self.nickName.text]&&[self.user.sign isEqualToString:self.signature.text]) {
        
        
        return;
    }
    
    
    self.setUserInfo = [[OSetUserInfo alloc] initWithCallBack:@selector(callBack:) for:self];
    self.setUserInfo.sex = @"0";
    self.setUserInfo.zone = @"0";
    self.setUserInfo.nick = self.nickName.text;
    
    self.setUserInfo.signature = self.signature.text;
    
    NSLog(@"self.nickName == %@,self.signature == %@",self.nickName.text,self.signature.text);
    if (self.nickName.text ==nil) {
        self.setUserInfo.nick = @"";
        
    }
    if (self.signature.text == nil) {
        self.setUserInfo.signature = @"";
    }
    [self.setUserInfo request];



}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
  

}

-(void)callBack:(OBaseLogic *)log
{

    OUserInfo* info = [OUserInfo getInfo];
    if (!info) {
        info = [[OUserInfo alloc] init];
    }
//    info.region = self.setUserInfo.zone;
    info.sign = self.setUserInfo.signature;
    info.nickName = self.setUserInfo.nick;
    info.sex = [self.setUserInfo.sex boolValue];
    info.icon = self.setUserInfo.icon;
    
    [OUserInfo setInfo:info];
    
    NSLog(@"newUser == %@,%@%@",self.setUserInfo.sex,self.setUserInfo.nick,self.setUserInfo.signature);
    NSString *sr = [self.setUserInfo.signature stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"---%@",sr);

    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshInfo" object:nil];
    [self.tableView reloadData];
    

}

//相机按钮事件
-(void)CameraAction
{
    NSLog(@"相机");
    //创建弹出列表
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选取",@"取消", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"从相册选取" otherButtonTitles:@"取消", nil];
    }
    //给列表一个tag值
    sheet.tag = 255;
    [sheet showInView:self.view];
}
//实现actionSheet delegate事件
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        //数据类型 进行相应操作
        NSUInteger sourceType = 0;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 2:
                    // 取消
                    return;
                case 0:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 1) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        //UIImagePickerController协议
        imagePickerController.delegate = self;
        //允许编辑
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        //模态到相机或相册页面
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}
//实现ImagePicker delegate 事件
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{//模态消失
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = [myasset defaultRepresentation];
        NSString *fileName = [representation filename];
        self.imageName = fileName;
    
        
        NSLog(@"image == %@,imageName == %@",image,self.imageName);
        if (image != nil && self.imageName != nil) {
            [self upLoadImage:image andImageName:self.imageName andUrl:@"http://192.168.1.103:9099/OServer/OSetUserInfo"];
            //http://192.168.1.27:9000/os/ks/add
            //http://192.168.1.103:9099/OServer/OSetUserInfo
        }
    };
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init] ;
    [assetslibrary assetForURL:imageURL
                   resultBlock:resultblock
                  failureBlock:nil];

    // 保存图片至本地，方法见下文
    [self saveImage:image withName:@"currentImage.png"];
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
    
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
    NSData *data = [NSData dataWithContentsOfFile:fullPath];
    
    self.image.image = [UIImage imageWithData:data];
    
    self.isFullScreen = NO;
    [self.imageView setImage:savedImage];
    self.imageView.tag = 10000;
//    [self.tableView reloadData];
    
}
//保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}
//实现点击图片预览功能，滑动放大缩小，带动画
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    self.isFullScreen = !self.isFullScreen;
    UITouch *touch = [touches anyObject];
    
    CGPoint touchPoint = [touch locationInView:self.view];
    
    CGPoint imagePoint = self.imageView.frame.origin;
    //touchPoint.x ，touchPoint.y 就是触点的坐标
    
    // 触点在imageView内，点击imageView时 放大,再次点击时缩小
    if(imagePoint.x <= touchPoint.x && imagePoint.x +self.imageView.frame.size.width >=touchPoint.x && imagePoint.y <=  touchPoint.y && imagePoint.y+self.imageView.frame.size.height >= touchPoint.y)
    {
        // 设置图片放大动画
        [UIView beginAnimations:nil context:nil];
        // 动画时间
        [UIView setAnimationDuration:1];
        
        if (self.isFullScreen) {
            // 放大尺寸
            
            self.imageView.frame = CGRectMake(0, 0, 320, 480);
        }
        else {
            // 缩小尺寸
            self.imageView.frame = CGRectMake(50, 65, 90, 115);
        }
        
        // commit动画
        [UIView commitAnimations];
        
    }
    
}


//上传图片
-(void)upLoadImage:(UIImage *)upImage andImageName:(NSString *)imageName andUrl:(NSString *)url
{
    
    
    //创建管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //存放非文件参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.nickName.text forKey:@"nick"];
    [params setObject:@"0" forKey:@"sex"];
//    [params setObject:self.signature.text forKey:@"signature"];

    //发送请求

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    NSLog(@"imagename == %@",imageName);
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    
        NSData *fileData = UIImageJPEGRepresentation(upImage, 1.0);
        
        [formData appendPartWithFileData:fileData name:@"headFile" fileName:imageName mimeType:@"image/jpeg"];
   
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *response = responseObject;
        
        self.user.icon = [response objectForKey:@"icon"];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshInfo" object:nil];
        NSLog(@"imageName == %@",imageName);
     
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        
    }];

   
}


//tableview协议方法

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    if (indexPath.section == 0 && indexPath.row == 0 ) {
        
//           [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        cell.textLabel.text = @"头像";
        self.image = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - 80, 10, 60*Proportion, 60*Proportion)];
        
//        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
//        NSData *data = [NSData dataWithContentsOfFile:fullPath];
//        
//        
//        [[SDImageCache sharedImageCache]clearDisk];
//        [[SDImageCache sharedImageCache]clearMemory];
   
       
        [self.image sd_setImageWithURL:[NSURL URLWithString:self.user.icon]];
        
        [cell addSubview:self.image];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        cell.textLabel.text = @"ID";
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH - 120, 10, 100, 30)];
        label.textAlignment = NSTextAlignmentRight;
        label.font = [UIFont systemFontOfSize:15*Proportion];
        [cell addSubview:label];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    if (indexPath.section == 0 && indexPath.row == 2) {
        cell.textLabel.text = @"昵称";
        self.nickName = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH - 120, 10, 100, 30)];
        self.nickName.textAlignment = NSTextAlignmentRight;
//        self.nickName.text = [DataBaseHandel shareBaseData].nickName;
        self.nickName.text = self.user.nickName;
        self.nickName.font = [UIFont systemFontOfSize:15*Proportion];
        [cell addSubview:self.nickName];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    if (indexPath.section == 0 && indexPath.row == 3) {
        cell.textLabel.text = @"二维码";
        UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - 50, 10 , 30*Proportion, 30*Proportion)];
        view.image = [UIImage imageNamed:@"erweima"];
        [cell addSubview:view];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        cell.textLabel.text = @"性别";
        UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - 40, 10 , 30*Proportion, 30*Proportion)];
        if (self.user.sex ==0) {
        
            view.image = [UIImage imageNamed:@"nan.jpg"];
        }else if (self.user != 0){
        
            view.image = [UIImage imageNamed:@"nv.jpg"];
        }
        [cell addSubview:view];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    if (indexPath.section == 1 && indexPath.row == 1) {
        cell.textLabel.text = @"地域";
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH - 120, 10, 100, 30)];
        label.textAlignment = NSTextAlignmentRight;
        label.text = self.zone;
        label.font = [UIFont systemFontOfSize:15*Proportion];
        [cell addSubview:label];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    if (indexPath.section == 1 && indexPath.row == 2) {
        cell.textLabel.text = @"签名";
        self.signature = [[UILabel alloc]initWithFrame:CGRectMake(70, 10, WIDTH - 90, cell.frame.size.height-10)];
        self.signature.textAlignment = NSTextAlignmentRight;
        self.signature.font = [UIFont systemFontOfSize:15*Proportion];
        self.signature.text = self.user.sign;
        [cell addSubview:self.signature];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    cell.textLabel.font = [UIFont systemFontOfSize:15*Proportion];
    return cell;
}
//cell数

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    
    return 3;
    
}
//区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
//点击触发方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSLog(@"头像");
//       调用相机方法
        [self CameraAction];
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSLog(@"ID");
        OMainDetailViewController *view = [[OMainDetailViewController alloc]init];
        view.type = 1;
        [self.navigationController pushViewController:view animated:YES];
    }
    if (indexPath.section == 0 && indexPath.row == 2) {
        NSLog(@"昵称");
        OMainDetailViewController *view = [[OMainDetailViewController alloc]init];
        view.type = 2;
        view.nickDelegate = self;
        [self.navigationController pushViewController:view animated:YES];
    }
    if (indexPath.section == 0 && indexPath.row == 3) {
        NSLog(@"二维码");
        OMainDetailViewController *view = [[OMainDetailViewController alloc]init];
        view.type = 3;
        [self.navigationController pushViewController:view animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSLog(@"性别");
        
        
        
    }
    if (indexPath.section == 1 && indexPath.row == 1) {
        NSLog(@"地域");
        OMainDetailViewController *view = [[OMainDetailViewController alloc]init];
        view.type = 4;
        [self getPosition];

//        [self.navigationController pushViewController:view animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 2) {
        NSLog(@"签名");
        OMainDetailViewController *view = [[OMainDetailViewController alloc]init];
        view.type = 5;
        view.nickDelegate = self;
        [self.navigationController pushViewController:view animated:YES];
    }
}
//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 80*Proportion;
    }
    return 50*Proportion;
}

//传递昵称协议方法
-(void)bringNickname:(NSString *)nickName
{
    [DataBaseHandel shareBaseData].nickName = nickName;
    self.nickName.text = nickName;
}


-(void)bringSignature:(NSString *)signature
{

    NSLog(@"名 == %@",signature);
    self.signature.text = signature;

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
